package cn.edu.neusoft.wuguangsheng.flowerimpression.fragment;


import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.io.File;

import cn.edu.neusoft.wuguangsheng.flowerimpression.CircleImageView;
import cn.edu.neusoft.wuguangsheng.flowerimpression.R;
import cn.edu.neusoft.wuguangsheng.flowerimpression.activity.AllKnowCollectionActivity;
import cn.edu.neusoft.wuguangsheng.flowerimpression.activity.AllKnowCommentActivity;
import cn.edu.neusoft.wuguangsheng.flowerimpression.activity.DialogThridUtils;
import cn.edu.neusoft.wuguangsheng.flowerimpression.activity.LoginActivity;
import cn.edu.neusoft.wuguangsheng.flowerimpression.activity.SetUserActivity;
import cn.edu.neusoft.wuguangsheng.flowerimpression.activity.UserFanKuiActivity;
import cn.edu.neusoft.wuguangsheng.flowerimpression.activity.WeiboDialogUtils;
import cn.edu.neusoft.wuguangsheng.flowerimpression.bean.SuccessBean;
import cn.edu.neusoft.wuguangsheng.flowerimpression.bean.UserInfoBean;
import cn.edu.neusoft.wuguangsheng.flowerimpression.listener.TListener;
import cn.edu.neusoft.wuguangsheng.flowerimpression.model.SetUserHandPhotoModel;
import cn.edu.neusoft.wuguangsheng.flowerimpression.model.UserInfoModel;
import cn.edu.neusoft.wuguangsheng.flowerimpression.service.Service;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */

public class WoDFragment extends BaseFragment implements View.OnClickListener {

    TextView user_name_tv;
    TextView user_phone_tv;
    TextView user_pic,user_cancel;

    LinearLayout my_set_info,my_fankui,my_lxwm;
    Button logout_btn;

    private String phone;
    private String email;
    public static final int CHOOSE_PHOTO = 2;

    CircleImageView circleImageView;

    private Dialog dialog;
    private View inflate;

    private File imageFile;
    private String userid;
    private Dialog mDialog;

    private boolean up = false;

    TextView user_shoucang_tv;
    TextView user_pinglun_tv;


    @Override
    void initView() {
        user_name_tv = (TextView)view.findViewById(R.id.user_name_tv);
        user_phone_tv = (TextView)view.findViewById(R.id.user_phone_tv);
        my_set_info = (LinearLayout)view.findViewById(R.id.my_set_info);
        circleImageView = (CircleImageView)view.findViewById(R.id.user_photo_iv);
        my_fankui = (LinearLayout)view.findViewById(R.id.my_fankui);

        user_shoucang_tv = (TextView)view.findViewById(R.id.user_shoucang_tv);
        user_pinglun_tv = (TextView)view.findViewById(R.id.user_pinglun_tv);
        my_lxwm = (LinearLayout)view.findViewById(R.id.my_lxwm);
        logout_btn = (Button)view.findViewById(R.id.logout_btn);

         userid = getid();
        UserInfoModel userInfoModel = new UserInfoModel();
        userInfoModel.getUserInfo(userid,userInfoBeanTListener);
    }

    @Override
    void initEvent() {
        my_set_info.setOnClickListener(this);
        circleImageView.setOnClickListener(this);
        user_shoucang_tv.setOnClickListener(this);
        user_pinglun_tv.setOnClickListener(this);
        my_fankui.setOnClickListener(this);
        my_lxwm.setOnClickListener(this);
        logout_btn.setOnClickListener(this);

    }

    @Override
    void initDate() {

    }

    public WoDFragment() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.my_set_info:
                Intent intent = new Intent(getContext(), SetUserActivity.class);
                intent.putExtra("phone",phone);
                intent.putExtra("email",email);
                startActivity(intent);
                break;
            case R.id.user_photo_iv:

                show(view);
               break;
            case R.id.user_pic:
               // Toast.makeText(getContext(),"11111",Toast.LENGTH_SHORT).show();
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }
                else{
                    openAlbum();
                    dialog.dismiss();
                }
               break;
            case R.id.user_cancel:
                dialog.dismiss();
                break;
            case R.id.user_pinglun_tv:
               Intent intent1 = new Intent(getContext(), AllKnowCommentActivity.class);
               startActivity(intent1);
                break;
            case R.id.user_shoucang_tv:
                Intent intent2 = new Intent(getContext(), AllKnowCollectionActivity.class);
                startActivity(intent2);
                break;
            case R.id.my_fankui:
                Intent intent3 = new Intent(getContext(), UserFanKuiActivity.class);
                startActivity(intent3);
                break;
            case R.id.my_lxwm:
                AlertDialog alertDialog=new AlertDialog.Builder(getActivity())
                        .setIcon(R.drawable.video_icon)
                        .setTitle("温馨提示")
                        .setMessage("您确认要联系管理员吗？")
                        .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //创建打电话的意图
                                Intent intentp = new Intent();
                                //设置拨打电话的动作
                                intentp.setAction(Intent.ACTION_CALL);
                                //设置拨打电话的号码
                                intentp.setData(Uri.parse("tel:" + "17385442159"));
                                //开启打电话的意图
                                startActivity(intentp);

                            }
                        })
                        .setPositiveButton("取消",null)
                        .create();
                alertDialog.show();
                break;
            case R.id.logout_btn:
                AlertDialog alertDialog1=new AlertDialog.Builder(getActivity())
                        .setIcon(R.drawable.video_icon)
                        .setTitle("温馨提示")
                        .setMessage("您确认要退出登录吗？")
                        .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intentsp=new Intent(getContext(),LoginActivity.class);
                                startActivity(intentsp);
                                clearPass();
                                getActivity().finish();

                            }
                        })
                        .setPositiveButton("取消",null)
                        .create();
                alertDialog1.show();
                break;
        }

    }

    private void openAlbum(){
        Intent intentp = new Intent("android.intent.action.GET_CONTENT");
        intentp.setType("image/*");
        startActivityForResult(intentp,CHOOSE_PHOTO);
    }

    TListener<UserInfoBean> userInfoBeanTListener=new TListener<UserInfoBean>() {
        @Override
        public void onResponse(UserInfoBean userInfoBean) {
            String user_nickname = userInfoBean.getUser_nickname();
            String user_sex = userInfoBean.getUser_sex();
            phone = userInfoBean.getUser_phone();
            email = userInfoBean.getUser_email();

            String sex;
            if (user_sex.equals("1")){
                 sex = "先生你好";
            }
            else{
                 sex = "女士你好";

            }
            if (userInfoBean.getUser_photo().equals("1") || userInfoBean.getUser_photo().equals("1.jpg")){
                if (user_sex.equals("1")){
                    circleImageView.setImageResource(R.mipmap.nanshi);
                }
                else{
                    circleImageView.setImageResource(R.mipmap.nvshi);
                }
            }
            else{
                String img = Service.BASE_URL+"flower_impression/public/uploads/"+userInfoBean.getUser_photo();
                Picasso.with(getContext()).load(img).into(circleImageView);
            }

            user_name_tv.setText(user_nickname+sex);
            user_phone_tv.setText(phone);
        }

        @Override
        public void onFail(String msg) {

        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT>=19){
                        handleImageOnKitkat(data);
                    } else {
                        handleImageOnKitkat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){

            case 1:
                //Toast.makeText(getActivity(),"3333",Toast.LENGTH_SHORT).show();
                if (grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                } else {
                    Toast.makeText(getContext(),"you the",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(getContext(),uri)){
            //如果是document类型的uri 则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];//解析出数字的格式
                String selection = MediaStore.Images.Media._ID+"="+id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            } else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null);
            } else if("content".equalsIgnoreCase(uri.getScheme())){
                imagePath = getImagePath(uri,null);
            } else if("file".equalsIgnoreCase(uri.getScheme())){
                imagePath = uri.getPath();
            }
                upload();
        }
        //Toast.makeText(getActivity(),"222222",Toast.LENGTH_SHORT).show();
    }



    private void upload(){
        if (imageFile != null && imageFile.exists()){
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),imageFile);
            MultipartBody.Part part = MultipartBody.Part.createFormData("image",imageFile.getName(),body);

           // Toast.makeText(getContext(),userid+"----"+imageFile,Toast.LENGTH_SHORT).show();
            mDialog = WeiboDialogUtils.createLoadingDialog(getContext(), "上传中...");
            SetUserHandPhotoModel setUserHandPhotoModel = new SetUserHandPhotoModel();
            setUserHandPhotoModel.setUserHandPhoto(part,userid,successBeanTListenerp);
        }
       // Toast.makeText(getContext(),"11111",Toast.LENGTH_LONG).show();
    }
    TListener<SuccessBean> successBeanTListenerp = new TListener<SuccessBean>() {
        @Override
        public void onResponse(SuccessBean successBean) {
            if (successBean.getSuccess().equals("1")){
                Toast.makeText(getActivity(),"上传 成功",Toast.LENGTH_SHORT).show();
               initView();
               initEvent();
               initDate();
            }
            else if (successBean.getSuccess().equals("3")){
                Toast.makeText(getActivity(),"上传头像大小不可超过1M！",Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getActivity(),"上传 失败",Toast.LENGTH_SHORT).show();
            }
            DialogThridUtils.closeDialog(mDialog);
        }

        @Override
        public void onFail(String msg) {
            Toast.makeText(getActivity(),"上传 111",Toast.LENGTH_SHORT).show();
            DialogThridUtils.closeDialog(mDialog);
        }
    };

    private String getImagePath(Uri uri, String selection) {
        String path =null;
        Cursor cursor =getActivity().getContentResolver().query(uri,
                null,selection,null,null);
        if(cursor != null){
            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        imageFile = new File(path);
        return path;
    }
    public void show(View view){
        dialog = new Dialog(getContext(),R.style.DialogTheme);
        //填充对话框的布局
        inflate = LayoutInflater.from(getContext()).inflate(R.layout.setphoto_view, null);
        //初始化控件
        user_pic = (TextView) inflate.findViewById(R.id.user_pic);
        user_pic.setOnClickListener(this);
//        camera = (TextView) inflate.findViewById(R.id.camera);

       user_cancel = (TextView) inflate.findViewById(R.id.user_cancel);
       user_cancel.setOnClickListener(this);
//        camera.setOnClickListener(this);
        //user_photo.setOnClickListener(this);
//        cancel.setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity( Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        setLayout_file(R.layout.fragment_wo_d);
        return super.onCreateView(inflater,container,savedInstanceState);
    }


    @Override
    public void onPause() {
        super.onPause();
        up = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (up) {
            initView();
            initEvent();
            initDate();
            up = false;
        }
    }




}
